import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes,constantRoutesTest, dynamicRoutes_hd, dynamicRoutes_xd,dynamicRoutes_jk,dynamicRoutes_mx,dynamicRoutes_public,dynamicRoutes_Admin } from '@/router'
// import { getRouters } from '@/api/menu' 
import {getRouters } from '@/api/user/index' 
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import useUserStore from '@/store/modules/user'
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

// import useAppStore from '@/store/modules/app'
// const appStore = useAppStore()

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: [],
      routesAll:[],
      userType: ''
    }),
    actions: {
      setRoutes(routes) {
        this.addRoutes = routes
        this.routes = constantRoutes.concat(routes)
      },
      setDefaultRoutes(routes) {
        this.defaultRoutes = constantRoutes.concat(routes)
      },
      setTopbarRoutes(routes) {
        this.topbarRouters = routes
      },
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      setRoutesAll(routes) { //全部接口路由
        this.routesAll = routes
      },
      generateRoutesJc(companyRole='', tagName='') {  //请求-过滤-路由（侧边栏）
        let userInfo = useUserStore().getUser()
        let test:any = []
        test = dynamicRoutes //路由集合
           return new Promise(resolve => {  
            getRouters(userInfo.id).then((res) => {
              // debugger 
              let sdata=[]
              let menuList=res.data
              console.log('userInfo.userType',userInfo.userType)
              let dataList = JSON.parse(JSON.stringify(menuList)) //12级菜单
              let companyRole = localStorage.getItem('companyRole')
              let tagName=localStorage.getItem('tagName')
                console.log('companyRole111',companyRole)
        console.log('tagName111',tagName)
              let statusOen='' //1级菜单的状态
              let statusTwo='' //二级菜单的显示状态
              let publicPut= JSON.parse(JSON.stringify(dynamicRoutes_public))   //公用菜单 
              let sdataAll=[]                                  
              if(userInfo.userType==1){ //平台方
                statusOen='admin'
                statusTwo='admin'
                sdata = JSON.parse(JSON.stringify(dynamicRoutes_Admin)) 
                sdataAll=JSON.parse(JSON.stringify(dynamicRoutes_Admin))                      
              }else{
                //companyRole - 'zx','putBox','cars','sellBox' //货代 集装箱公司 集卡 卖箱
                 dataList.forEach(item => {
                    item.children.forEach(intemInfo=>{
                      sdataAll=[...sdataAll, ...intemInfo.children,]                       
                    })                             
                  });

                    if(companyRole){
                      statusOen=companyRole
                      statusTwo=tagName
                        dataList.forEach(item => {
                          if(item.companyRole==statusOen){
                            item.children.forEach(intemInfo=>{                           
                              if(intemInfo.companyRole==statusTwo){
                                sdata = JSON.parse(JSON.stringify(intemInfo.children))

                              }
                              // parentRolesParam.push(intemInfo.companyRole)
                            })
                          }
                        
                      });
                    }else{
                      statusOen= dataList[0]?.name
                       statusTwo=dataList[0]?.children[0].name
                       console.log('statusTwo',statusTwo)
                        dataList.forEach(item => {
                          if(item.name==statusOen){
                            item.children.forEach(intemInfo=>{
                              if(intemInfo.name==statusTwo){
                                sdata = JSON.parse(JSON.stringify(intemInfo.children))
                              }
                            })
                          }
                        
                      });
                      // if(statusOen=='zx'){
                      //   sdata = JSON.parse(JSON.stringify(dynamicRoutes_hd))                             
                      // }else if(statusOen=='putBox'){
                      //    sdata = JSON.parse(JSON.stringify(dynamicRoutes_xd))
                      // }else if(statusOen=='cars'){
                      //    sdata = JSON.parse(JSON.stringify(dynamicRoutes_jk))
      
                      // }else if(statusOen=='sellBox'){
                      //    sdata = JSON.parse(JSON.stringify(dynamicRoutes_mx))
                        
                      // }
                    }
                    // sdata=sdata.concat(publicPut) //合并公用
                    // console.log('sdata11',sdata)

              }
            //   dataList.forEach(item => {
            //     if(item.companyRole==status){
            //       item.children.forEach(intemInfo=>{
            //         parentRolesParam.push(intemInfo.companyRole)
            //       })
            //     }
              
            // });
              // addCompanyRole(constantRoutesTest)
              // console.log('test',test)
              // console.log('dataList',dataList)
              // console.log('55555555',sdataAll)
              const rdata = JSON.parse(JSON.stringify(sdataAll))
              const rewriteRoutes = filterAsyncRouter(rdata, false, true) //全部路由
             
              const testerSync=JSON.parse(JSON.stringify(sdata)) //左侧菜单数据
              // const testerSyncRout = filterCompanyRoleRouter(testerSync,statusTwo, statusOen)  //数据过滤
              const testerSyncRout = filterAsyncRouter(testerSync)  //数据过滤
              console.log('testerSyncRout',testerSyncRout)
            // console.log('testerSync',testerSyncRout)
            this.setRoutesAll(dataList)//全部接口路由
            // this.setRoutes(dataList)//全部接口路由
            // this.setDefaultRoutes(dataList)//全部接口路由


              this.setSidebarRouters(testerSyncRout)//左侧菜单显示
              resolve(rewriteRoutes)
            })
           })

      },

    }
  })

// 递归校验router page菜单
function filterCompanyRoleRouter(arry = [], tagName = '', companyRole = '', parentRolesParam = []) {
// return false
  let router = arry.filter(item => {
  
    let parentRoles:any = []

    // if (!item.roles && !parentRolesParam) {
    //   return false
    // }else{
    //   parentRoles = item.roles || parentRolesParam 
    // }
    if(item?.hidden==1){
      return false
    }
    if (item.children != null && item.children && item.children.length) {
        item.children = filterCompanyRoleRouter(item.children,tagName,companyRole,parentRoles)
    } else {
      delete item['children']
      delete item['redirect']
    }

    // if (item.children) {
    //   item.children = filterCompanyRoleRouter(item.children,tagName,companyRole,parentRoles)
    // }else{

    // }
    if (item.meta) {
      // let roles = parentRoles
      // let tags = item.meta.tags 
      if (item?.hidden==0) {
        return true
      }
    }
    return false
  })
  return router
}
// function filterCompanyRoleRouter(arry = [], tagName = '', companyRole = '', parentRolesParam = []) {
// // return false
//   let router = arry.filter(item => {
//     let parentRoles:any = []

//     if (!item.roles && !parentRolesParam) {
//       return false
//     }else{
//       parentRoles = item.roles || parentRolesParam 
//     }

//     if (item.children) {
//       item.children = filterCompanyRoleRouter(item.children,tagName,companyRole,parentRoles)
//     }
//     if (item.meta) {
//       let roles = parentRoles
//       let tags = item.meta.tags 
//       if (roles && tags && roles.indexOf(companyRole) != -1 && tags.indexOf(tagName) != -1) {
//         return true
//       }
//     }
//     return false
//   })
//   return router
// }

// 遍历后台传来的路由数组，转换为路由格式对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        route.component = loadView(route.component)
        // if(route.type==2 && route.meta.title=="订单管理"){
        //   console.log('555555',2)
        //   route.alwaysShow=true
        // }else{
        //   route.alwaysShow=false

        // }
        // route.alwaysShow=false
      }
    }
    if (route.children != null && route.children && route.children.length) {
        // route.children = route.children.filter(c=>c?.hidden==0)
        route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}
// function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
//   return asyncRouterMap.filter(route => {
//     if (type && route.children) {
//       route.children = filterChildren(route.children)
//     }
//     if (route.component) {
//       // Layout ParentView 组件特殊处理
//       if (route.component === 'Layout') {
//         route.component = Layout
//       } else if (route.component === 'ParentView') {
//         route.component = ParentView
//       } else {
//         route.component = loadView(route.component)
//       }
//     }
//     if (route.children != null && route.children && route.children.length) {
//         route.children = filterAsyncRouter(route.children, route, type)
//     } else {
//       delete route['children']
//       delete route['redirect']
//     }
//     return true
//   })
// }

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el))
        return
      }
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}


export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    // console.log('modules',dir)
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
}

export default usePermissionStore
